package com.example.zhinongbao.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.example.zhinongbao.contract.SchoolContract;
import com.example.zhinongbao.model.SchoolModel;
import com.example.zhinongbao.provider.NewsDao;

import java.util.Objects;

public class SchoolPresenter implements SchoolContract.Presenter {
    private static final String TAG = "SchoolPresenter";

    private SchoolContract.View view;
    private final SchoolModel model;
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    public SchoolPresenter(Context context) {
        Objects.requireNonNull(context, "Context cannot be null");
        this.model = new SchoolModel(context.getApplicationContext());
    }

    @Override
    public void attachView(SchoolContract.View view) {
        this.view = view;
    }

    @Override
    public void detachView() {
        this.view = null;
    }

    @Override
    public void getSchoolNews() {
        new Thread(() -> {
            try {
                String[][][] newsData = model.getSchoolNewsData();
                if (newsData != null && newsData.length > 0) {
                    notifySuccess(newsData);
                } else {
                    notifyError("暂无新闻数据");
                }
            } catch (Exception e) {
                notifyError("数据加载失败: " + e.getMessage());
            }
        }).start();
    }

    @Override
    public void publishNews(String title, String content, String imageUrl) {
        new Thread(() -> {
            boolean success = model.publishNews(title, content, imageUrl);
            if (success) {
                mainHandler.post(() -> {
                    if (view != null) {
                        view.onPublishSuccess();
                        // 发布成功后自动刷新列表
                        getSchoolNews();
                    }
                });
            } else {
                notifyError("新闻发布失败");
            }
        }).start();
    }

    // 新增方法：获取新闻详情
    public void getNewsDetail(long newsId) {
        new Thread(() -> {
            NewsDao.NewsItem newsItem = model.getNewsDetail(newsId);
            if (newsItem != null) {
                mainHandler.post(() -> {
                    if (view != null) {
                        // 需要View层实现onDetailLoaded回调
                        if (view instanceof EnhancedSchoolView) {
                            ((EnhancedSchoolView) view).onDetailLoaded(newsItem);
                        }
                    }
                });
            } else {
                notifyError("未找到该新闻");
            }
        }).start();
    }

    // 新增方法：删除新闻
    public void deleteNews(long newsId) {
        new Thread(() -> {
            boolean success = model.deleteNews(newsId);
            if (success) {
                mainHandler.post(() -> {
                    if (view != null) {
                        // 需要View层实现onNewsDeleted回调
                        if (view instanceof EnhancedSchoolView) {
                            ((EnhancedSchoolView) view).onNewsDeleted(newsId);
                        }
                        // 刷新列表
                        getSchoolNews();
                    }
                });
            } else {
                notifyError("删除失败");
            }
        }).start();
    }

    private void notifySuccess(String[][][] newsData) {
        mainHandler.post(() -> {
            if (view != null) {
                String[] titles = new String[newsData.length];
                String[] contents = new String[newsData.length];
                String[] imageUrls = new String[newsData.length];

                for (int i = 0; i < newsData.length; i++) {
                    titles[i] = newsData[i][0][0];
                    contents[i] = newsData[i][1][0];
                    imageUrls[i] = newsData[i][2][0];
                }
                view.showSchoolNews(titles, contents, imageUrls);
            }
        });
    }

    private void notifyError(String message) {
        mainHandler.post(() -> {
            if (view != null) {
                view.showError(message);
            }
        });
    }

    // 增强的View接口（可选）
    public interface EnhancedSchoolView extends SchoolContract.View {
        void onDetailLoaded(NewsDao.NewsItem newsItem);
        void onNewsDeleted(long deletedNewsId);
    }
}